package com.imooc.mymall.intercepter;

import com.google.common.util.concurrent.RateLimiter;
import com.imooc.mymall.exception.BusinessException;
import com.imooc.mymall.exception.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h1>全局限流拦截器</h1>
 * @Author: crowsjian
 * @Date: 2020/7/15 18:57
 */
@Slf4j
@Component
public class RateLimitIntercepter implements HandlerInterceptor {

    /*限流器实例（QPS限制为10）*/
    private static final RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(!rateLimiter.tryAcquire()){
            log.error("系统已经被限流了。");
            throw new BusinessException(ErrorCodeEnum.RATE_LIMIT_ERROR);
        }
        return true;
    }
}
